package com.huaxin.dss2;


import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import com.huaxin.dss2.data.NewSmallStation.NewSignalR;
import com.huaxin.dss2.util.Constant;
import com.huaxin.dss2.util.LoggerType;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.apache.commons.daemon.support.DaemonLoader;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;


/**
 * Created by HX-119 on 2014/6/26.
 */
@Slf4j
public class Launcher implements Daemon {
    
    public static final String APP_PATH;

    static {
        File appRootFile = null;
        String jvmPropertyAppPath = System.getProperty("app.path");
        if(StringUtils.isEmpty(jvmPropertyAppPath)){
            appRootFile = new File(File.separator + System.getProperty("user.dir"));
        }else{
            appRootFile = new File(jvmPropertyAppPath);
        }
        try {
            log.info("app.path:{}", appRootFile.getCanonicalPath());
        } catch (IOException e) {
            log.error("应用程序路径读取失败",e);
            System.exit(1);
        }
        APP_PATH=System.getProperty("user.dir");
        log.info("应用路径:"+APP_PATH);
    }


    private void initLogBackCfg(String logbackConfigFile) {
        try {
            log.info("加载日志配置文件:" + logbackConfigFile);
            URL logURL = new URL("file:" + logbackConfigFile);
            ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
            LoggerContext loggerContext = (LoggerContext) loggerFactory;
            loggerContext.reset();
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(loggerContext);
            configurator.doConfigure(logURL);
        } catch (Exception e) {
            log.error("初始化logback失败:" + e.getMessage());
            System.exit(1);
        }
    }

    @Override
    public void init(DaemonContext daemonContext) throws Exception {
        /*
          获取启动参数数组
          index 0:启动模式 "production":生产模式
         */
        String[] args = daemonContext.getArguments();
        String logbackConf= null;
        //加载日志文件
        if (null != args && args.length > 0 && Objects.equals(LoggerType.production,(Constant.loggerType = LoggerType.getLoggerType(args[0])))) {
            logbackConf=APP_PATH + File.separator + "conf" + File.separator + "logback.xml";
        }else{
            logbackConf=APP_PATH + File.separator + "conf" + File.separator + "logback-console.xml";
        }
        //初始化日志
        initLogBackCfg(logbackConf);
    }

    /**
     * 启动
     * @throws Exception 异常
     */
    @Override
    public void start() throws Exception {
        // 加载spring文件
        new FileSystemXmlApplicationContext("classpath*:/spring/spring-*.xml");
        try {
            // 初始化连接
            NewSignalR.init();
            log.info("华信数据存储服务启动完成");
        }catch (Exception e){
             log.info("站点数据采集初始化失败:", e);
        }

    }

    @Override
    public void stop() throws Exception {
        System.exit(1);
    }

    @Override
    public void destroy() {
        System.exit(0);
    }

    /**
     * dss 启动入口
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        startup(args);
    }

    /**
     * 启动程序
     * @param args 参数列表
     * @throws Exception 异常
     */
    public static void startup(String[] args) throws Exception {
        LauncherLoad.startup(args);
    }

    /**
     * 结束程序
     * @throws Exception 异常
     */
    public static void shutdown() throws Exception {
        LauncherLoad.shutdown();
    }

    private static class LauncherLoad {
        private static Launcher launcher = new Launcher();

        /**
         * 启动方法
         * @param args 参数
         * @throws Exception 异常
         */
        public static void startup(String[] args) throws Exception {
            DaemonLoader.Context context = new DaemonLoader.Context();
            context.setArguments(args);
            launcher.init(context);
            launcher.start();
        }

        public static void shutdown() throws Exception {
            launcher.stop();
            launcher.destroy();
        }
    }

}
